<template>
  <div class="home-page">
    <!-- 移动端布局 -->
    <div v-if="appStore.isMobile" class="mobile-home" :style="{ height: `${layoutHeights.totalHeight}px` }">
      <!-- 日历区域 -->
      <div class="calendar-section" :style="{ height: `${layoutHeights.calendarHeight}px` }">
        <Calendar
          :selected-date="appStore.selectedDate"
          @update:selected-date="handleDateChange"
          @dayClick="handleDayClick"
        />
      </div>

      <!-- 事件列表区域 -->
      <div class="events-section" :style="{ height: `${layoutHeights.eventsHeight}px` }">
        <!-- <div class="events-header">
          <h3>今日事件</h3>
          <n-button size="small" @click="$router.push('/events/create')">
            <n-icon :size="16">
              <Add />
            </n-icon>
            添加
          </n-button>
        </div> -->
        
        <div class="events-header-mobile">
          <h3>{{ formatDate(appStore.selectedDate, 'MM月DD日') }} 事件</h3>
          <small style="color: #666;">{{ formatDate(appStore.selectedDate, 'YYYY-MM-DD') }}</small>
          <!-- 调试信息 -->
          <div v-if="false" style="font-size: 10px; color: #999; margin-top: 4px; line-height: 1.2;">
            屏幕: {{ layoutHeights.totalHeight }}px |
            日历: {{ layoutHeights.calendarHeight }}px |
            事件: {{ layoutHeights.eventsHeight }}px |
            底部: {{ layoutHeights.bottomNavHeight }}px<br>
            window.innerHeight: {{ window.innerHeight }}px |
            visualViewport: {{ window.visualViewport?.height || 'N/A' }}px
          </div>
        </div>

        <div class="events-list-container">
          <div class="events-list">
          <div v-if="selectedDateEvents.length === 0" class="empty-state">
            <n-icon :size="48" color="#ccc">
              <CalendarIcon />
            </n-icon>
            <p>{{ formatDate(appStore.selectedDate, 'MM月DD日') }} 没有事件</p>
            <n-button type="primary" @click="$router.push('/events/create')">
              创建事件
            </n-button>
          </div>

          <div v-else class="event-items">
            <div
              v-for="event in selectedDateEvents"
              :key="event.id"
              class="event-item"
              @click="handleEventClick(event)"
            >
              <div class="event-indicator" :style="{ backgroundColor: getEventColor(event) }"></div>
              <div class="event-content">
                <div class="event-title">{{ event.title }}</div>
                <div class="event-time">
                  {{ formatEventTime(event) }}
                </div>
              </div>
              <div class="event-actions">
                <n-button
                  size="small"
                  :type="event.is_completed ? 'success' : 'default'"
                  @click.stop="toggleEventCompletion(event)"
                >
                  <n-icon :size="16">
                    <Checkmark v-if="event.is_completed" />
                    <Ellipse v-else />
                  </n-icon>
                </n-button>
              </div>
            </div>
          </div>
          </div>
        </div>
      </div>
    </div>
    
    <!-- 桌面端布局 -->
    <div v-else class="desktop-home">
      <div class="home-header">
        <h1>待办日历</h1>
        <div class="header-actions">
          <n-button type="primary" @click="$router.push('/events/create')">
            <n-icon :size="16">
              <Add />
            </n-icon>
            创建事件
          </n-button>
        </div>
      </div>
      
      <div class="home-content">
        <!-- 左侧日历 -->
        <div class="calendar-panel">
          <Calendar
            :selected-date="appStore.selectedDate"
            @update:selected-date="handleDateChange"
            @dayClick="handleDayClick"
          />
        </div>
        
        <!-- 右侧事件列表 -->
        <div class="events-panel">
          <div class="panel-header">
            <h3>{{ formatDate(appStore.selectedDate, 'MM月DD日') }} 事件</h3>
            <small style="color: #666;">选中日期: {{ formatDate(appStore.selectedDate, 'YYYY-MM-DD') }}</small>
          </div>
          <div class="panel-content">
            <!-- 事件列表内容 -->
            <div v-if="selectedDateEvents.length === 0" class="empty-state">
              <n-icon :size="48" color="#ccc">
                <CalendarIcon />
              </n-icon>
              <p>该日期没有事件</p>
              <n-button type="primary" @click="$router.push('/events/create')">
                创建事件
              </n-button>
            </div>

            <div v-else class="event-items">
              <div
                v-for="event in selectedDateEvents"
                :key="event.id"
                class="event-item"
                @click="handleEventClick(event)"
              >
                <div class="event-indicator" :style="{ backgroundColor: getEventColor(event) }"></div>
                <div class="event-content">
                  <div class="event-title">{{ event.title }}</div>
                  <div class="event-time">{{ formatEventTime(event) }}</div>
                  <div v-if="event.description" class="event-description">{{ event.description }}</div>
                </div>
                <div class="event-actions">
                  <n-button
                    quaternary
                    circle
                    size="small"
                    @click.stop="toggleEventCompletion(event)"
                  >
                    <n-icon :size="16" :color="event.is_completed ? '#52c41a' : '#ccc'">
                      <Checkmark />
                    </n-icon>
                  </n-button>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import {
  Add,
  Calendar as CalendarIcon,
  Checkmark,
  Ellipse
} from '@vicons/ionicons5'
import { useRouter } from 'vue-router'
import { useAppStore } from '@/stores/app'
import { useEventsStore } from '@/stores/events'
import { formatDate } from '@/utils/date'
import { useMobileLayout } from '@/utils/device'
import type { Event, CalendarEvent } from '@/types'
import Calendar from '@/components/common/Calendar.vue'

const router = useRouter()
const appStore = useAppStore()
const eventsStore = useEventsStore()

// 移动端布局高度计算
const { layoutHeights } = useMobileLayout()

// 调试用的 window 对象引用
const window = globalThis.window

// 当前显示的日期（用于日历头部显示）
const currentDisplayDate = ref(new Date())

// 选中日期的事件
const selectedDateEvents = computed(() => {
  return eventsStore.getEventsByDate(appStore.selectedDate)
})

// 处理日期变化
const handleDateChange = (date: Date) => {
  appStore.setSelectedDate(date)
  currentDisplayDate.value = date
}

// 这些函数现在由 Calendar 组件内部处理
// const formatChineseDate = (date: Date) => { ... }
// const goToToday = () => { ... }

// 获取事件颜色
const getEventColor = (event: Event) => {
  const eventType = eventsStore.getEventType(event.event_type_id)
  return eventType?.color || '#2196F3'
}

// 格式化事件时间
const formatEventTime = (event: Event) => {
  if (event.start_time && event.end_time) {
    return `${event.start_time.substring(0, 5)} - ${event.end_time.substring(0, 5)}`
  } else if (event.start_time) {
    return event.start_time.substring(0, 5)
  }
  return '全天'
}

// 处理事件点击
const handleEventClick = (event: Event) => {
  // 跳转到事件详情页
  router.push(`/events/${event.id}`)
}

// 切换事件完成状态
const toggleEventCompletion = async (event: Event) => {
  await eventsStore.toggleEventCompletion(event.id, !event.is_completed)
}

// 处理日历日期点击
const handleDayClick = (date: Date, events: CalendarEvent[]) => {
  console.log('🏠 Home handleDayClick:', formatDate(date, 'YYYY-MM-DD'), `(${events.length} events)`)

  appStore.setSelectedDate(date)
  currentDisplayDate.value = date

  // 在移动端，如果有事件，显示提示信息
  if (appStore.isMobile && events.length > 0) {
    window.$message?.info(`${formatDate(date, 'MM月DD日')} 有 ${events.length} 个事件`)
  }
}

// 初始化
onMounted(async () => {
  await eventsStore.init()
  // 初始化当前显示日期
  currentDisplayDate.value = appStore.selectedDate
})
</script>

<style scoped>
.home-page {
  height: 100%;
}

/* 移动端样式 */
.mobile-home {
  display: flex;
  flex-direction: column;
  overflow: hidden;
  width: 100%;
}

.calendar-section {
  background: white;
  border-bottom: 1px solid #e0e0e0;
  flex-shrink: 0;
  overflow: hidden;
  position: relative;
}

.calendar-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 16px;
  border-bottom: 1px solid #f0f0f0;
}

.calendar-header h2 {
  font-size: 18px;
  font-weight: 600;
  color: #333;
}

/* 移动端日历区域样式已通过内联样式设置高度 */

.calendar-placeholder {
  height: 300px;
  background: #f9f9f9;
  border-radius: 8px;
  display: flex;
  align-items: center;
  justify-content: center;
  color: #666;
  border: 2px dashed #ddd;
}

.events-section {
  background: white;
  display: flex;
  flex-direction: column;
  flex-shrink: 0;
  overflow: hidden;
  position: relative;
}

.events-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 16px;
  border-bottom: 1px solid #f0f0f0;
}

.events-header h3 {
  font-size: 16px;
  font-weight: 600;
  color: #333;
}

.events-list-container {
  flex: 1;
  overflow-y: auto;
  min-height: 0;
}

.events-list {
  height: 100%;
}

.empty-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 40px 20px;
  text-align: center;
}

.empty-state p {
  margin: 16px 0;
  color: #666;
}

.event-items {
  padding: 8px 0;
}

.event-item {
  display: flex;
  align-items: center;
  padding: 12px 16px;
  border-bottom: 1px solid #f0f0f0;
  cursor: pointer;
  transition: background-color 0.2s ease;
}

.event-item:hover {
  background-color: #f9f9f9;
}

.event-indicator {
  width: 4px;
  height: 40px;
  border-radius: 2px;
  margin-right: 12px;
}

.event-content {
  flex: 1;
}

.event-title {
  font-size: 14px;
  font-weight: 500;
  color: #333;
  margin-bottom: 4px;
}

.event-time {
  font-size: 12px;
  color: #666;
}

.event-actions {
  margin-left: 12px;
}

/* 桌面端样式 */
.desktop-home {
  height: 100%;
  display: flex;
  flex-direction: column;
  padding: 24px;
}

.home-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 24px;
}

.home-header h1 {
  font-size: 28px;
  font-weight: 600;
  color: #333;
}

.header-actions {
  display: flex;
  gap: 12px;
}

.home-content {
  flex: 1;
  display: grid;
  grid-template-columns: 1fr 400px;
  gap: 24px;
  min-height: 0;
}

.calendar-panel,
.events-panel {
  background: white;
  border-radius: 12px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  overflow: hidden;
  display: flex;
  flex-direction: column;
}

.calendar-panel {
  min-height: 500px;
}

/* 日历面板样式现在由 Calendar 组件内部处理 */

.calendar-placeholder,
.events-placeholder {
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
  color: #666;
  border: 2px dashed #ddd;
  margin: 16px;
  border-radius: 8px;
}

.events-panel {
  display: flex;
  flex-direction: column;
}

.panel-header {
  padding: 20px;
  border-bottom: 1px solid #f0f0f0;
}

.panel-header h3 {
  font-size: 18px;
  font-weight: 600;
  color: #333;
}

.panel-content {
  flex: 1;
  overflow-y: auto;
}

.events-header-mobile {
  padding: 16px;
  background: white;
  border-bottom: 1px solid #f0f0f0;
  flex-shrink: 0;
}

.events-header-mobile h3 {
  margin: 0 0 4px 0;
  font-size: 16px;
  font-weight: 600;
  color: #333;
}

.events-header-mobile small {
  font-size: 12px;
}

/* 横屏模式优化 */
@media (max-width: 768px) and (orientation: landscape) {
  .mobile-home {
    flex-direction: row !important;
  }

  .calendar-section {
    width: 60% !important;
    height: 100% !important;
    border-right: 1px solid #e0e0e0;
    border-bottom: none;
  }

  .events-section {
    width: 40% !important;
    height: 100% !important;
  }

  .events-header-mobile {
    padding: 8px 12px;
  }

  .events-header-mobile h3 {
    font-size: 14px;
    margin-bottom: 2px;
  }

  .events-header-mobile small {
    font-size: 10px;
  }
}
</style>
